package home.my.recordmanage.dao;

import home.my.base.dao.BaseDao;
import home.my.base.util.DateUtil;
import home.my.recordmanage.model.DealIdea;
import home.my.recordmanage.model.Record;
import home.my.recordmanage.model.RecordSource;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;

public class RecordDao extends BaseDao<Record> {
	private DealIdeaDao dealIdeaDao;

	public java.util.List<Map<String, Object>> statRecord(java.util.Date beginDate, java.util.Date endDate)
    {
		/* 
		 * 共接手receieve笔，完成finish笔，其中历史遗留的history笔。共notFinished笔未完成记录，其中本期接手hisPassed笔，转交中passed笔。
		 * 接手的，录入时间符合条件 receieve
		 * 完成的，完成时间符合条件 finish 
		 * 完成中历史遗留的，完成时间符合条件，录入时间<beginDate， history
		 * 所有未完成，完成日期为空 notFinished 
		 * 本期未完成，完成日期为空，接手日期符合条件 hisPassed
		 * 完成日期为空，转手日期不为空 passed
		 */
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		Session session = this.getSession();
		Query query;
		//设置选择日期的起止部分
//		这里修改结束时间会把action里面的值也修改，变态。因此这句不能用
//		endDate.setDate(endDate.getDate() + 1);
		
//		Date newEndDate = new Date();
//		newEndDate.setTime(endDate.getTime());
//		newEndDate.setDate(newEndDate.getDate()+1);
		
		beginDate = DateUtil.zerolizedTime(beginDate);
		Date newEndDate = DateUtil.zerolizedTime(DateUtil.increaseDate(endDate, 1));
	
		//统计单据用sql
		String baseSql = "select count(*) from home.my.recordmanage.model.Record reco where 1=1 ";
		String receieve = baseSql+"and reco.receieveDate>=:beginDate and reco.receieveDate<:endDate and reco.source.id=:fkId";
		String finish = baseSql+"and reco.finishDate>=:beginDate and reco.finishDate<:endDate and reco.source.id=:fkId";
		String history = baseSql+"and reco.finishDate>=:beginDate and reco.finishDate<:endDate and reco.receieveDate<:beginDate and reco.source.id=:fkId";
		String notFinished = baseSql+"and reco.finishDate is null and reco.source.id=:fkId";
		String hisPassed = baseSql+"and reco.finishDate is null and reco.receieveDate>=:beginDate and reco.receieveDate<:endDate and reco.source.id=:fkId";
		String passed = baseSql+"and reco.finishDate is null and reco.partnerDate is not null and reco.source.id=:fkId";
		
		//取source列表
		String sqlSource = "from home.my.recordmanage.model.RecordSource rs order by rs.id";
		@SuppressWarnings("unchecked")
		List<RecordSource> sourceList = this.getHibernateTemplate().find(sqlSource);
		
		for(RecordSource source:sourceList){
			Map<String, Object> table = new HashMap<String, Object>();
			
			table.put("source", source.getName());
			
			query = session.createQuery(receieve);
			query.setLong("beginDate", beginDate.getTime());
			query.setLong("endDate", newEndDate.getTime());
			query.setLong("fkId", source.getId());
			table.put("receieve", query.iterate().next());
			
			query = session.createQuery(finish);
			query.setLong("beginDate", beginDate.getTime());
			query.setLong("endDate", newEndDate.getTime());			
			query.setLong("fkId", source.getId());
			table.put("finish", query.iterate().next());
			
			query = session.createQuery(history);
			query.setLong("beginDate", beginDate.getTime());
			query.setLong("endDate", newEndDate.getTime());			
			query.setLong("fkId", source.getId());
			table.put("history", query.iterate().next());
			
			query = session.createQuery(notFinished);
			query.setLong("fkId", source.getId());
			table.put("notFinished", query.iterate().next());
						
			query = session.createQuery(hisPassed);
			query.setLong("beginDate", beginDate.getTime());
			query.setLong("endDate", newEndDate.getTime());			
			query.setLong("fkId", source.getId());
			table.put("hisPassed", query.iterate().next());
			
			query = session.createQuery(passed);
			query.setLong("fkId", source.getId());
			table.put("passed", query.iterate().next());
			
			result.add(table);
		}
			
		return result;
    }

	public void updateRecord(Record pojo, String dealIdea,
			String needsFinishDate) {
		Date nowDate = new Date();
		Record dbRecord = this.load(pojo.getPk());
		if( ( dbRecord.getStatus()<STATUS.finished.value || "1".equals(needsFinishDate) ) && pojo.getStatus()>=STATUS.finished.value ){
			pojo.setFinishDate(nowDate.getTime());
			pojo.setFinishDateStr(DateUtil.formatDateTimeToStr(nowDate));
		}
		try {
//			BeanUtils.copyProperties(dbRecord, pojo);会把null值的日期给赋值成0，sb包
			dbRecord.setCompany(pojo.getCompany());
			dbRecord.setContact(pojo.getContact());
			dbRecord.setErrorType(pojo.getErrorType());
			dbRecord.setFinishDate(pojo.getFinishDate());
			dbRecord.setFinishDateStr(pojo.getFinishDateStr());
			dbRecord.setIsBad(pojo.getIsBad());
			dbRecord.setLinkUrl(pojo.getLinkUrl());
			dbRecord.setPartner(pojo.getPartner());
			dbRecord.setPartnerDateStr(pojo.getPartnerDateStr());
			dbRecord.setPhone(pojo.getPhone());
			dbRecord.setProblemDesc(pojo.getProblemDesc());
			dbRecord.setReceieveDate(pojo.getReceieveDate());
			dbRecord.setReceieveDateStr(pojo.getReceieveDateStr());
			dbRecord.setSource(pojo.getSource());
			dbRecord.setStatus(pojo.getStatus());
			dbRecord.setSubmitPerson(pojo.getSubmitPerson());
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("复制属性出错："+e.getMessage());
		}
		this.update(dbRecord);
		saveDealIdea(dealIdea,dbRecord.getId());
	}


	@Override
	public void delete(Record entity) {
		SQLQuery qu = this.getSession().createSQLQuery("delete from " + new DealIdea().getTableName() + " where 1=1 and record_fk=:id");
		qu.setLong("id", entity.getId()).executeUpdate();
		super.delete(entity);
	}

	public void createRecord(Record record, String dealIdea) {
		java.util.Date now = new java.util.Date();
		record.setReceieveDate(now.getTime());
		record.setReceieveDateStr(DateUtil.formatDateTimeToStr(now));
//		record.setStatus(STATUS.dealing.value);
		if( record.getStatus()>=STATUS.finished.value ){
			Date nowDate = new Date();
			record.setFinishDate(nowDate.getTime());
			record.setFinishDateStr(DateUtil.formatDateTimeToStr(nowDate));
		}
		Long id = this.create(record);
		saveDealIdea(dealIdea,id);
	}
	
	private void saveDealIdea(String dealIdea,Long recordId) {
		if(StringUtils.isNotEmpty(dealIdea)){
			java.util.Date now = new java.util.Date();
			DealIdea idea = new DealIdea();
			idea.setRecordFk(recordId);
			idea.setIdea(dealIdea);
			idea.setIdeaDate(now.getTime());
			idea.setIdeaDateStr(DateUtil.formatDateTimeToStr(now));
			dealIdeaDao.create(idea);
		}
	}
	
	public List<Map<String, Object>> fixErrorRecords(){
		Session session = this.getSession();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String,Object> map = new HashMap<String,Object>();
		
		String fixZeroFinishDateSql = "update record set finish_date=receieve_date,finish_date_str=receieve_date_str where status>=3  and (finish_date is null or finish_date=0) ";
		int zeroDateCount = session.createSQLQuery(fixZeroFinishDateSql).executeUpdate();
		map.put("name","修复已完成单据的空白完成时间：");
		map.put("value",zeroDateCount);
		list.add(map);
		
		String fixZeroFinishDateSql2 = "update record set finish_date=null where finish_date=0";
		int zeroDateCount2 = session.createSQLQuery(fixZeroFinishDateSql2).executeUpdate();
		map = new HashMap<String,Object>();
		map.put("name","修复其他单据的空白完成时间：");
		map.put("value",zeroDateCount2);
		list.add(map);
		
		String fixZeroPartnerDateSql = "update record set partner_Date=null where partner_Date=0";
		int partnerDateCount = session.createSQLQuery(fixZeroPartnerDateSql).executeUpdate();
		map = new HashMap<String,Object>();
		map.put("name","修复转交单据的空白转交时间：");
		map.put("value",partnerDateCount);
		list.add(map);
		
		return list;
	}
	
	public void setDealIdeaDao(DealIdeaDao dealIdeaDao) {
		this.dealIdeaDao = dealIdeaDao;
	}
}